//资产负债表
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:zywz/generated/assets.dart';
import 'package:zywz/pages/report/tax_report.dart';

import '../../api/api_client.dart';
import '../../bloc/report/report_bloc.dart';
import '../../bloc/report/report_data.dart';
import '../../bloc/report/report_event.dart';
import '../../dialog/showBtm.dart';
import 'blance_qyzw_tax.dart';
import 'blance_tax.dart';


class TaxBalanceSheetReport  extends StatelessWidget {
  const TaxBalanceSheetReport({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => ReportBloc(apiClient: ApiClient.instance),
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          scaffoldBackgroundColor: const Color(0xFFF7F9FC), // 背景色
          appBarTheme: const AppBarTheme(
            backgroundColor: Colors.white,
            elevation: 0,
            centerTitle: true,
            titleTextStyle: TextStyle(
              color: Colors.black,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        home: TaxBalanceSheetPage(),
      ),
    );
  }
}




// 纳税列表项数据模型
class TaxItem {
  final String title;
  final Color color;
  final double value;

  const TaxItem({
    required this.title,
    required this.color,
    this.value = 0.00,
  });
}

class TaxBalanceSheetPage extends StatefulWidget {
  const TaxBalanceSheetPage({super.key});

  @override
  State<TaxBalanceSheetPage> createState() => _TaxBalanceSheetPageState();
}

class _TaxBalanceSheetPageState extends State<TaxBalanceSheetPage>
    with SingleTickerProviderStateMixin{


  int getCurrentQuarter() {
    final now = DateTime.now();
    return (now.month - 1) ~/ 3 + 1;
  }

  // 或者更详细的方法
  String getCurrentQuarterString() {
    final now = DateTime.now();
    final quarter = (now.month - 1) ~/ 3 + 1;
    switch (quarter) {
      case 1:
        return '第一季度';
      case 2:
        return '第二季度';
      case 3:
        return '第三季度';
      case 4:
        return '第四季度';
      default:
        return '第一季度'; // 默认值
    }
  }
  // 或者更详细的方法
  String getCurrentJd(int caseOp) {
    switch (caseOp) {
      case 1:
        return '第一季度';
      case 2:
        return '第二季度';
      case 3:
        return '第三季度';
      case 4:
        return '第四季度';
      default:
        return '第一季度'; // 默认值
    }
  }


  var jidu = '第一季度';
  var jiduIndex = 0;
  var yearIndex = 0;
  var titleShow ="(2025) 第一季度";

  final List<String> jiduStart = ['01', '03', '06', '09'];
  final List<String> jiduEnd = ['03', '06', '09', '12'];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: tabs.length, vsync: this);

    var selectedYear = DateTime.now().year;
    yearIndex = 0;
    jidu = getCurrentQuarterString();
    jiduIndex = getCurrentQuarter()-1;
    titleShow = "($selectedYear) $jidu";

    context.read<ReportBloc>().add(LoadReportBalanceData( "$selectedYear${jiduStart[jiduIndex]}", "$selectedYear${jiduEnd[jiduIndex]}",'资产'));
    context.read<ReportBloc>().add(LoadReportBalanceQyZwData( "$selectedYear${jiduStart[jiduIndex]}", "$selectedYear${jiduEnd[jiduIndex]}",'负债'));
  }


  late TabController _tabController;
  final PageController? pageController = PageController();

  List tabs = ["资产", "负债和权益"];


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.black, size: 20),
          onPressed: () {
            // 返回上一页的逻辑
            context.pop();
            // context.push('/WheelPickerExample');
          },
        ),
        title: const Text('资产负债表'),
      ),
      body: Container(
        color: Colors.white,
        child: Column(
          children: [
            // 时间选择器区域
            _buildTimeSelector(context),
            Expanded(child: Column(
              children: [
                TabBar(
                  overlayColor: MaterialStateProperty.all(Colors.transparent),
                  indicatorColor: Color(0xFF4DD0E1),
                  dividerHeight: 0.0,
                  controller: _tabController,
                  onTap: (index) {
                    pageController?.jumpToPage(index);
                  },
                  tabs: tabs.map((e) {
                    return Tab(
                      text: e,
                    );
                  }).toList(),
                ),
                Expanded(child: PageView(
                  onPageChanged: (index) {
                    _tabController.index = index;
                  },
                  controller: pageController,
                  children:  [
                    BlanceTax(title: '资产',type: '资产',),
                    BlanceQyzwTax(title: '负债和权益',type: '负债',),
                  ],
                ))
              ],
            )),

            // const SizedBox(height: 10),
            // // 纳税列表
            // _buildTaxList(),
          ],
        ),
      ),
    );
  }

  // 构建时间选择器
  Widget _buildTimeSelector(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      alignment: Alignment.center,
      child: GestureDetector(
        onTap: () async {
          var dataMap= await  showSlectSheet1(
            context,
            indexYear: yearIndex,
            jiduItem: jiduIndex,
            callBack: (year, jidu) {
              print('$year $jidu');
              var selectedYear = DateTime.now().year;
              setState(() {
                yearIndex = year;
                jiduIndex = jidu;

                titleShow = "(${selectedYear - year}) ${getCurrentJd(jidu+1)}";
              });

              context.read<ReportBloc>().add(LoadReportBalanceData( "$selectedYear${jiduStart[jiduIndex]}", "$selectedYear${jiduEnd[jiduIndex]}",'资产'));
              context.read<ReportBloc>().add(LoadReportBalanceQyZwData( "$selectedYear${jiduStart[jiduIndex]}", "$selectedYear${jiduEnd[jiduIndex]}",'负债'));
            },
          );

          print("dataMap $dataMap");

        },
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              titleShow,
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
              ),
            ),
            const Icon(Icons.arrow_drop_down),
          ],
        ),
      ),
    );
  }



  // 构建纳税列表
  Widget _buildTaxList() {
    return BlocConsumer<ReportBloc, ReportState>(
        buildWhen: (previous, current) {
          if (current is ReportTaxReportSuccess) {
            return true;
          }
          return false;
        },
        listener: (context, state) {
          if (state is ReportLoadFailure) {

          }
        },
        builder: (context, state) {
          if (state is ReportTaxReportSuccess) {
            return Container(
              margin: const EdgeInsets.symmetric(horizontal: 16.0),
              padding: const EdgeInsets.all(16.0),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                  BoxShadow(
                    color: Colors.grey.withOpacity(0.1),
                    spreadRadius: 1,
                    blurRadius: 5,
                    offset: const Offset(0, 3),
                  ),
                ],
              ),
              child: Column(
                // children: taxItems.map((item) => TaxListItem(item: item)).toList(),
                // children:[...(state.map((item) => TaxListItem(keyItem: '1', valueItem: '2')).toList())],
                children: state.reportData.entries.map((entry) =>
                    TaxListItemX(
                        keyItem: entry.key,
                        valueItem: entry.value?.toString() ?? ''
                    )).toList(), // 注意这里需要 toList()
                // children: [],
              ),
            );
          } else {
            return Container();
          }
        });
  }

}




